#! /usr/bin/env python
# coding=utf-8


from Bio import SeqIO
import os
import shutil
import argparse
import sys
import re



parser = argparse.ArgumentParser(
    description=''' 对cutadaptor 结果的长度进行过滤 取 特定长度的
    用法:
    filter_barcode_len.py  -i cutprimer -o filter_len -l 648 -s 668
    由大天才于2022年3月22日创建于浙江农业大学''')

parser.add_argument('-i',
                help='minibar.py输出的分配好的fastq文件')

parser.add_argument('-s',
                help='short read length')

parser.add_argument('-l',
                help='long read length')


parser.add_argument('-o',
                help='输出的目录')

args = parser.parse_args()


if not args.i or not args.o:
    parser.print_help()
    sys.exit()




infile = args.i

outfile = args.o

if not args.s:
	s = 658-10
else:
	s = int(args.s)

if not args.l:
	l = 658+10
else:
	l = int(args.l)



try:
	shutil.rmtree(outfile)
except:
	pass
try:
	os.mkdir(outfile)
except:
	pass


n = 0
m = 0

for i in os.listdir(infile):
	save_lista = []
	for j in SeqIO.parse(infile+'/'+i,'fastq'):
		if len(str(j.seq))>=s and len(str(j.seq))<=l:
			save_lista.append(j)
	if len(save_lista)>0:
		n +=1
		f = open(outfile+'/'+i,'w')
		for j in save_lista:
			SeqIO.write(j,f,'fastq')
			m +=1
		f.close()

print('we get %s reads from %s  specimens' % (m,n))
